#include "arch.h"
#include "mhn-regs.h"
#include "config.h"
#include "time.h"
#include "irq.h"

/* jiffies should be defined as volatile */
volatile unsigned long jiffies=0;
volatile unsigned long jiffies_div10=0;

void TimerInit(void)
{
    u32 old_rcnr = RCNR;
    
    /* disable timer interrupts and clear the AL and HZ bits*/
    RTSR = (RTSR_AL | RTSR_HZ);

    /* put the counter to 0 */
    /* strange enough, this doesn't seem to work -- Erik */
    /* RCNR = 0x0; */

    /* RCNR writes may be delayed by a 32-kHz clock cycle */
    RCNR = 0x0;
    
    while (RCNR > old_rcnr);
    
    /* os timer */
    cli();
    OSCR = 0;
    OSMR0 = (3250000L)/TIMER_TICK_PER_SEC ; /* Trigger interrupts every 10 ms */
    OSSR = 0xFFF;
    OIER = OIER_E0;

    /* Interrupt Initailization routine */
    ICCR = 0;
    ICLR = 0;
    ICMR = IRQ_OST0;
    ICMR2 = 0;
    sti();

}

/* returns the time in seconds */
u32  TimerGetTime(void)
{
    return (u32)RCNR;
}

/* returns the time in 1/100seconds */
u32  TimerGetCentiTime(void)
{
    return((u32) jiffies/(TIMER_TICK_PER_SEC*100));
}

void ostdelay(int uSec);
void msleep(unsigned int ms)
{
    ostdelay(1000*ms);
}

void msleep_cli(unsigned int ms)
{
    unsigned long init_jiffies;

    init_jiffies = OSCR;
    
    while( (init_jiffies + (unsigned long)(ms / 10) ) > OSCR ) {;}

}

void ostdelay(int uSec)
{
    unsigned long time = OSCR;
    unsigned long expireTime = time + (uSec * 3);   // approx 3 ticks per uS;

    //
    // Check if we wrapped on the expireTime
    // and delay first part until wrap
    //
    if (expireTime < time)
    {
        while (time < OSCR) {
        }
    }

    while (OSCR <= expireTime){
    }

    return ;
}
